package com.ruoyi.shop.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.shop.domain.ShopProductImage;
import com.ruoyi.shop.domain.ShopSupplier;
import com.ruoyi.shop.domain.vo.ProductCategoryVo;
import com.ruoyi.shop.service.IShopProductCategoryService;
import com.ruoyi.shop.service.IShopProductImageService;
import com.ruoyi.shop.service.IShopSupplierService;
import com.ruoyi.shop.util.ImageUtils;
import com.ruoyi.shop.vo.ImageVo;
import com.ruoyi.shop.vo.ProductVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.shop.domain.ShopProduct;
import com.ruoyi.shop.service.IShopProductService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 商品Controller
 * 
 * @author Alan Zhang
 * @date 2021-09-14
 */
@Controller
@RequestMapping("/shop/product")
public class ShopProductController extends BaseController
{
    private String prefix = "shop/product";

    @Autowired
    private IShopProductService shopProductService;

    @Autowired
    private IShopSupplierService shopSupplierService;
    @Autowired
    private IShopProductCategoryService shopProductCategoryService;
    @Autowired
    private IShopProductImageService shopProductImageService;

    @RequiresPermissions("shop:product:view")
    @GetMapping()
    public String product(ModelMap mmap)
    {
        putShopSupplierList(mmap);
        return prefix + "/product";
    }

    /**
     * 查询商品列表
     */
    @RequiresPermissions("shop:product:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ShopProduct shopProduct)
    {
        startPage();
        List<ShopProduct> list = shopProductService.selectShopProductList(shopProduct);
        return getDataTable(list);
    }

    /**
     * 导出商品列表
     */
    @RequiresPermissions("shop:product:export")
    @Log(title = "商品", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ShopProduct shopProduct)
    {
        List<ShopProduct> list = shopProductService.selectShopProductList(shopProduct);
        ExcelUtil<ShopProduct> util = new ExcelUtil<ShopProduct>(ShopProduct.class);
        return util.exportExcel(list, "商品数据");
    }

    /**
     * 新增商品
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        putShopSupplierList(mmap);
        List<ProductCategoryVo> categoryList = shopProductCategoryService.selectSimpleShopProductCategoryAll();
        mmap.put("categoryList",categoryList);
        return prefix + "/add";
    }

    /**
     * 新增保存商品
     */
    @RequiresPermissions("shop:product:add")
    @Log(title = "商品", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestParam(value = "file", required = false) MultipartFile file, ShopProduct shopProduct) throws IOException {

        Long id = shopProductService.selectShopProductByProductName(shopProduct.getTitle());
        if(id != null){
            return AjaxResult.error("商品名称已存在");
        }
        if(file != null) {
            shopProduct.setThumbnail(ImageUtils.uploadProduct(file));
        }
        return toAjax(shopProductService.insertShopProduct(shopProduct));
    }

    /**
     * 修改商品
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        ShopProduct shopProduct = shopProductService.selectShopProductById(id);
        mmap.put("shopProduct", shopProduct);
        List<ProductCategoryVo> categoryList = shopProductCategoryService.selectSimpleShopProductCategoryAll();
        mmap.put("categoryList",categoryList);
        putShopSupplierList(mmap);
        return prefix + "/edit";
    }


    //供应商
    private void putShopSupplierList(ModelMap mmap){
        ShopSupplier param = new ShopSupplier();
        param.setDelFlag(0);//正常
        List<ShopSupplier> shopSupplierList = shopSupplierService.selectShopSupplierList(param);
        mmap.put("shopSupplierList", shopSupplierList);
    }


    /**
     * 修改保存商品
     */
    @RequiresPermissions("shop:product:edit")
    @Log(title = "商品", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestParam(value = "file", required = false) MultipartFile file,ShopProduct shopProduct) throws IOException {
        Long id = shopProductService.selectShopProductByProductName(shopProduct.getTitle());
        if(id != null && !shopProduct.getId().equals(id)){
            return AjaxResult.error("商品名称已存在");
        }
        if(file != null) {
            shopProduct.setThumbnail(ImageUtils.uploadProduct(file));
        }
        return toAjax(shopProductService.updateShopProduct(shopProduct));
    }

    /**
     * 删除商品
     */
    @RequiresPermissions("shop:product:remove")
    @Log(title = "商品", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(shopProductService.deleteShopProductByIds(ids));
    }

    /**
     * 导入数据 模板
     * @return
     */
    @GetMapping("/importTemplate/{type}")
    @ResponseBody
    public AjaxResult importTemplate(@PathVariable("type") Integer type)
    {
        if(1 == type){
            return importProductTemplate();
        } else {
            return importProductPriceTemplate();
        }
    }

    public AjaxResult importProductTemplate()
    {
        ExcelUtil<ProductVo> util = new ExcelUtil<ProductVo>(ProductVo.class);
        return util.importTemplateExcel("商品导入");
    }

    public AjaxResult importProductPriceTemplate()
    {
        ExcelUtil<ProductVo> util = new ExcelUtil<ProductVo>(ProductVo.class);
        return util.importTemplateExcel("同步商品导入");
    }


    /**
     * 导入数据
     */
    @RequiresPermissions("shop:product:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, Long supplierId) throws Exception
    {
        ExcelUtil<ProductVo> util = new ExcelUtil<ProductVo>(ProductVo.class);
        List<ProductVo> dataList = util.importExcel(file.getInputStream());
        String optName = ShiroUtils.getSysUser().getLoginName();
        String message = shopProductService.importProductInfo(dataList, supplierId, optName);
        return AjaxResult.success(message);
    }


    /**
     * 导入数据
     */
    @RequiresPermissions("shop:product:import")
    @PostMapping("/importPriceData")
    @ResponseBody
    public AjaxResult importPriceData(MultipartFile file, Long supplierId) throws Exception
    {
        ExcelUtil<ProductVo> util = new ExcelUtil<ProductVo>(ProductVo.class);
        List<ProductVo> dataList = util.importExcel(file.getInputStream());
        String optName = ShiroUtils.getSysUser().getLoginName();
        String message = shopProductService.importProductPrice(dataList, supplierId, optName);
        return AjaxResult.success(message);
    }


    /**
     * 上传/已上传图片显示页面
     * @param productId
     * @param mmap
     * @return
     */
    @GetMapping("/upload/image")
    public String uploadImage(Long productId, ModelMap mmap)
    {
        ShopProductImage param = new ShopProductImage();
        param.setProductId(productId);
        List<ShopProductImage> productImageList = shopProductImageService.selectShopProductImageList(param);
        List<String> urlList = new ArrayList<>();
        List<ImageVo> imageVoList = new ArrayList<>();
        final String url = "/system/del/img/1";
        for (ShopProductImage image : productImageList){
            urlList.add(image.getImgSrc());

            ImageVo imageVo = new ImageVo();
            imageVo.setCaption("");
            imageVo.setUrl(url);
            imageVo.setKey(image.getId());
            imageVoList.add(imageVo);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("url", urlList);
        ajax.put("config", imageVoList);
        mmap.put("imgInfo",ajax);
        mmap.put("productId",productId);
        return prefix + "/uploadimage";
    }


    /**
     * 存入数据库
     * 新增保存图片
     */
    @RequiresPermissions("shop:product:upload:image")
    @Log(title = "产品图-保存", businessType = BusinessType.INSERT)
    @PostMapping("/uploadImage")
    @ResponseBody
    public AjaxResult uploadImage(ShopProductImage sgProductImage)
    {
        int rows = shopProductImageService.insertShopProductImage(sgProductImage);
        if(rows>0) {
            AjaxResult ajax = new AjaxResult();

            ajax.put("code", 0);
            ajax.put("msg", "上传成功!");
            ajax.put("imgId", sgProductImage.getId());
            return ajax;
        }else{
            return error("上传失败!");
        }
    }
}
